package dk.snaveponyklub.servlets;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dk.snaveponyklub.handler.Handler;
import dk.snaveponyklub.handler.HandlerFactory;
import dk.snaveponyklub.util.Logger;

@SuppressWarnings("serial")
public class AdminServlet extends HttpServlet {

	private Handler aHandler = HandlerFactory.getInstance();

	public AdminServlet() {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		setIEHeaders(resp);
		String requestUrl = req.getRequestURL().toString();
		System.out.println("GET " + requestUrl);
		String value = requestUrl.substring(requestUrl.lastIndexOf('/') + 1);
		if (requestUrl.contains("page")) {
			resp.getWriter().println(getMainpage());
		} else {
			if (requestUrl.contains("persons")) {
				if (value.equals("persons")) {
					resp.getWriter().println(aHandler.getPersonList());
				} else {
					try {
						int id = Integer.parseInt(value);
						String xml = aHandler.getPerson(id);
						if (xml != null)
							resp.getWriter().println(xml);
						else
							resp.sendError(HttpServletResponse.SC_NOT_FOUND);
					} catch (NumberFormatException e) {
						Logger.error(value + " is not number");
						resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Not a valid person id");
					}
				}
			} else {
				if (requestUrl.contains("timeslots")) {
					try {
						int week = Integer.parseInt(value);
						String xml = aHandler.getWeekTimeSlots(week);
						if (xml != null)
							resp.getWriter().println(xml);
						else
							resp.sendError(HttpServletResponse.SC_NOT_FOUND);
					} catch (NumberFormatException e) {
						Logger.error(value + " is not number");
						resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Not a valid week number");
					}
				} else {
					if (requestUrl.contains("horses")) {
						if (value.equals("horses")) {
							resp.getWriter().println(aHandler.getHorseList());
						} else {
							try {
								int id = Integer.parseInt(value);
								String xml = aHandler.getHorse(id);
								if (xml != null)
									resp.getWriter().println(xml);
								else
									resp.sendError(HttpServletResponse.SC_NOT_FOUND);
							} catch (NumberFormatException e) {
								Logger.error(value + " is not number");
								resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Not a valid horse id");
							}
						}
					} else {
						resp.getWriter().println(getMainpage());
					}
				}
			}
		}
	}

	private void setIEHeaders(HttpServletResponse resp) {
		// Then IE also is ok
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("Pragma", "no-cache");
		resp.setHeader("Expires", "-1");
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		setIEHeaders(resp);
		String requestUrl = req.getRequestURL().toString();
		System.out.println("PUT " + requestUrl);
		if (requestUrl.contains("persons")) {
			String xml = convertStreamToString(req.getInputStream());
			System.out.println("XML: " + xml);
			try {
				aHandler.addPerson(xml);
			} catch (Throwable e) {
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
			}
		} else {
			if (requestUrl.contains("horses")) {
				String xml = convertStreamToString(req.getInputStream());
				System.out.println("XML: " + xml);
				try {
					aHandler.addHorse(xml);
				} catch (Throwable e) {
					resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
				}
			} else {
				if (requestUrl.contains("timeslots")) {
					String xml = convertStreamToString(req.getInputStream());
					System.out.println("XML: " + xml);
					try {
						aHandler.addTimeslot(xml);
					} catch (Throwable e) {
						resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
					}
				} else {
					resp.getWriter().println(getMainpage());
				}
			}
		}
	}

	public String convertStreamToString(InputStream is) throws IOException {
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {
			return "";
		}
	}

	private String getMainpage() {
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<?xml-stylesheet type=\"text/xsl\" href=\"http://127.0.0.1:8080/snaveponyklub/xsl/MainPage.xsl\"?>"
				+ "<persist xmlns=\"http://www.snaveponyklub.dk\"></persist>";
	}
}